/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core.reactor.os;

import com.googlecode.actorom.impl.core.reactor.MessageDemultiplexer;
import com.googlecode.actorom.impl.core.reactor.MessageDispatcher;
import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageHandler;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class OSMessageDispatcher implements MessageDispatcher {

    private final Map<Object, MessageHandler> handlers = new HashMap<Object, MessageHandler>();
    private final Set busyHandlers = new HashSet();
    private final ExecutorService handlerExecutor;
    private final boolean fair;
    private volatile Thread selectorThread = null;
    private volatile boolean active = false;

    public OSMessageDispatcher(int threadPoolSize) {
        this(threadPoolSize, false);
    }

    public OSMessageDispatcher(int threadPoolSize, boolean fair) {
        this.handlerExecutor = Executors.newFixedThreadPool(threadPoolSize);
        this.fair = fair;
    }

    public synchronized void registerHandler(Object key, MessageHandler handler) {
        handlers.put(key, handler);
    }

    public synchronized void unregisterHandler(Object key) {
        handlers.remove(key);
    }

    public void dispatch(final MessageDemultiplexer messageDemultiplexer, final MessageQueue messageQueue) {
        if (!active) {
            active = true;
            selectorThread = new Thread() {

                @Override
                public void run() {
                    while (active) {
                        try {
                            messageDemultiplexer.select(messageQueue);
                            try {
                                List<MessageHandle> selectedHandles = messageDemultiplexer.acquireSelectedMessages();
                                process(messageDemultiplexer, messageQueue, selectedHandles);
                            } finally {
                                messageDemultiplexer.releaseSelectedMessages();
                            }
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            };
            selectorThread.start();
        }
    }

    public void shutdown() {
        if (active) {
            active = false;
            selectorThread.interrupt();
            handlerExecutor.shutdownNow();
        }
    }

    private synchronized void process(MessageDemultiplexer messageDemultiplexer, MessageQueue messageQueue, List<MessageHandle> handles) {
        Iterator<MessageHandle> iterator = handles.iterator();
        int totalHandlers = handlers.size();
        int totalBusyHandlers = busyHandlers.size();
        int busyMessages = 0;
        while (iterator.hasNext() && totalHandlers > totalBusyHandlers && passFairnessCheck(busyMessages)) {
            MessageHandle handle = iterator.next();
            Object key = handle.getKey();
            if (!busyHandlers.contains(key)) {
                MessageHandler handler = handlers.get(key);
                busyHandlers.add(key);
                totalBusyHandlers++;
                iterator.remove();
                execute(messageDemultiplexer, messageQueue, handle, handler);
            } else {
                busyMessages++;
            }
        }
    }

    private void execute(final MessageDemultiplexer messageDemultiplexer, final MessageQueue messageQueue, final MessageHandle handle, final MessageHandler handler) {
        handlerExecutor.execute(new Runnable() {

            public void run() {
                handler.handle(handle);
                free(handle);
                messageDemultiplexer.wakeUp(messageQueue);
            }
        });
    }

    private synchronized void free(MessageHandle handle) {
        busyHandlers.remove(handle.getKey());
    }

    private boolean passFairnessCheck(int numberOfBusyMessages) {
        if (fair) {
            return true;
        } else {
            return numberOfBusyMessages < 100;
        }
    }
}
